import { use, useEffect,useState } from "react"
import { 
  getTableData,
  updateArticle,
  getArticleByTitle,
  getArticleByDateTime,
  getArticleByStatus,
  getArticleDetailById,
  deleteArticle,
  getArticleById
} from "@/api/modules/articleApi"
import { useNavigate } from "react-router-dom";

import type { TableProps,PopconfirmProps,GetProps,ConfigProviderProps } from 'antd';
import {DatePicker,Tooltip, Button, message, Space, Table, Popconfirm, Tag, Modal, Form, Input, Switch, Select } from 'antd';
import {DeleteOutlined, FormOutlined, PlusOutlined} from '@ant-design/icons'
import dayjs from "dayjs"
import TextArea from "antd/es/input/TextArea";
import ArticleDetail from './detail'
import MyEditor from "./MyEditor";
import { useSelector } from "react-redux";

type SizeType = ConfigProviderProps['componentSize'];
import { nanoid } from "nanoid";
type SearchProps = GetProps<typeof Input.Search>;
const { Search } = Input;
const { RangePicker } = DatePicker;

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const ArticleList = ()=>{
  const [form] = Form.useForm();
  const navigate = useNavigate()

  const { articleContentData } = useSelector(state=>state.articleSlice)
  const confirm: PopconfirmProps['onConfirm'] = (id:any) => {
    deleteNewsById(id)
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 表格表头
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (_,record) => {
        return (
          <Tooltip title="点击查看文章详情">
            <a onClick={()=>getArticleDetail(record.id)}>{record.id}</a>
          </Tooltip>
        )
      },
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '板块',
      key: 'region',
      dataIndex: 'region',
      render: (_, { region }) => (
        <>
        {region}
        </>
      ),
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (_, {status}) => (
        <Tag color={status ? 'green' : "volcano"} key={status}>
          {status ? '发布' : '未发布'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button icon={<FormOutlined />} type="primary" onClick={()=>updateNews(record)}>更新</Button>
          <Popconfirm
            title="删除"
            description="确定要删除该数据吗?"
            onConfirm={()=>confirm(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button icon={<DeleteOutlined />} type="primary" danger >删除</Button>
          </Popconfirm>
          
        </Space>
      ),
    },
  ];
  
  const [newsList,setNewsList] = useState([]) // 存储表格数据
  const [current,setCurrent] = useState(1)  // 当前页码
  const [pageSize,setPageSize] = useState(5) // 默认每页显示条数
  const [total,setTotal] = useState(newsList.length)  // 总的数据条数
  const [articleId,setArticleId] = useState()  // 文章id
  const [isPublish,setIsPublish] = useState(false)  // 文章发布状态
  const [size, setSize] = useState<SizeType>('middle');
  const [articleDetail,setArticleDetail] = useState([]) // 文章详情
  const [isArticleDetailModalOpen,setIsArticleDetailModalOpen] = useState(false)
  const [artilceContent,setArticleContent] = useState('')

  // 获取文章详情
  const getArticleDetail = async (id:any)=>{
    // 显示弹框
    setIsArticleDetailModalOpen(true)
    // 通过点击传递文章id获取文章详情
    let res = await getArticleDetailById(id)
    console.log(res,'res1111')
    if(res.status === 200){
      setArticleDetail(res.data.data)
    }
  }

  // 点击关闭文章详情模态框
  const handleDetailCancel = ()=>{
    setIsArticleDetailModalOpen(false)
  }

  // 提交更新表单数据,实现数据更新
  const onFinish = async (values)=>{
    console.log(articleId,values,'values')

    let newValues = {
      ...values,
      content:articleContentData
    }


    console.log(newValues,'newValues')


    let res = await updateArticle(articleId,newValues)
    // console.log(res,'res')
    if(res.status == 200){
      message.success('更新成功')
      getLists() // 重新获取数据
      handleCancel()
    }
  }
  // 回显文章内容在form表单
  const updateNews = async (news)=>{
    // 显示模态框
    setIsModalOpen(true)
    // 获取指定文章数据
    let res = await getArticleById(news.id)
    //存储文章id
    setArticleId(news.id)
    // 判断
    if(res.status == 200){
      // 存储当前文章内容
      let content = res.data.data[0].content

      // 存储文章内容
      setArticleContent(content)

      let newNews = {
        ...news,
        content
      }
      // 当前的文章内容回显到form表单
      form.setFieldsValue(newNews)
      console.log(newNews,'newNews')
    }

    
  }
  // 删除文章
  const deleteNewsById = async (articleId:any)=>{
    let res = await deleteArticle(articleId)
    console.log(res,'res')
    if(res.data.status === 200){
      message.success('删除成功')
      getLists()
    }
  } 

  // 获取文章列表数据
  const getLists = async ()=>{
    try {
      let res = await getTableData()
      if(res.status === 200 && res.data.length > 0){
        let newArr = res.data.map(item=>({
          key:item.id,
          id:item.id,
          title:item.title,
          author:item.author,
          createTime:dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss'),
          region:item.region,
          status:item.status
        }))
        setNewsList(newArr)
      }
    } catch (error) {
      
    }
    
  }
  // 组件挂载完毕时执行
  useEffect(()=>{
    getLists()
  },[])

  // 关闭模态框
  const handleCancel = ()=>{
    setIsModalOpen(false)
  }

  // 实现搜索方法
  const onSearch: SearchProps['onSearch'] = async (value:string) => {
    let res = await getArticleByTitle(value)
    let news = res.data.data // 搜索到的文章数组
    if(res.status === 200){ // 状态码为 200 表示获取数据成功
     let newArr =  news.map(item=>{ // 遍历处理数据格式
        return {
          ...item,
          key:nanoid()  // table表格列表需要有一个key属性,所以这里做一下处理
        }
      })
      // 修改 newsLIst 文章数据
      setNewsList(newArr) 
    }
  }

  // 获取时间周期数据
  const getDateTime = async (dates:any,dateStrings: [string, string])=>{
    // 用时间戳示进行时间处理
    let arr = dates?.map(item=>{
      return dayjs(item)?.valueOf() // 转换为时间戳
    })
    // 调接口获取数据
    let res = await getArticleByDateTime(arr)
    let times = res?.data?.data  // 搜索到的数据
    if(res?.status === 200){
      let newTimes = times?.map(item=>{ // 遍历处理数据格式 增加key属性 以及显示时间的格式处理
        return {
          ...item,
          key:nanoid(),
          createTime:dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        }
      })
      setNewsList(newTimes)
    }
    
  }

  // 根军文章状态进行筛选
  const onChangehandle = async (value:number)=>{
    // console.log(typeof value,'value')
    let res = await getArticleByStatus(value)
    console.log(res,'res');
    let newRes = res?.data?.data.map(item=>{
      return {
        ...item,
        key:nanoid(),
        createTime:dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
      }
    })

    setNewsList(newRes)
    
  }

  return <div>
    {/* 搜索框 */}
    <Space>
      <Button type="primary" icon={<PlusOutlined />} onClick={()=>navigate('/sys/article/add')}>新增</Button>
      {/* 根据关键字进行搜索 */}
      <Search
        placeholder="请输入文章标题"
        enterButton="搜索"
        size="middle"
        onSearch={onSearch}
        className="search-input"
      />
      {/* 时间周期进行搜索 */}
      
      <RangePicker 
        onChange={getDateTime}
        format="YYYY-MM-DD HH:mm:ss"
        size={size}
        needConfirm
        placeholder={['开始时间', '结束时间']}
      />
      {/* 根据状态进行搜索 */}
      <Select
        showSearch
        placeholder="筛选"
        optionFilterProp="label"
        onChange={onChangehandle}
        onSearch={onSearch}
        options={[
          {
            value: 1,
            label: '发布',
          },
          {
            value: 0,
            label: '未发布',
          }
        ]}
      />
    </Space>
    <Table<DataType> 
      columns={columns} 
      dataSource={newsList}  
      pagination={{
        total,
        current,
        pageSize,
        pageSizeOptions:[3,5,10,20], // 设置每页可以显示多少条数据
        showQuickJumper:true, // 是否可以快速跳转至某页
        showSizeChanger:true, // 是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
        onChange: (page, pageSize) => {
          setCurrent(page)
          setPageSize(pageSize)
        },
        showTotal: (total) => `共 ${total} 条数据`  // 显示当前数据总条数的文本
      }}
    />

    {/* 更新模态框 */}
    <Modal
        title="编辑"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        footer={null}
        // onOk={handleOk}
        onCancel={handleCancel}
        // okText="确定"
        // cancelText="取消"
        width={800}
      >
        <Form
          form={form}
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          wrapperCol={{ flex: 1 }}
          colon={false}
          style={{ maxWidth: 800 }}
          onFinish={onFinish}
        >
          <Form.Item label="文章标题" name="title" >
            <Input />
          </Form.Item>

          <Form.Item label="作者" name="author">
            <Input disabled />
          </Form.Item>

          <Form.Item label="区域" name="region">
            <Select>
              <Select.Option value="全球">全球</Select.Option>
              <Select.Option value="亚洲">亚洲</Select.Option>
              <Select.Option value="其他">其他</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="状态" name="status" >
            <Switch checkedChildren="发布" unCheckedChildren="未发布" defaultChecked={isPublish} onChange={(value)=>{
              setIsPublish(value)
            }}/>
          </Form.Item>

          <Form.Item name="content" label="新闻内容" >
            {/* <TextArea rows={4}/> */}
            <MyEditor artilceContent={artilceContent}/>
          </Form.Item>

          <Form.Item label=" ">
            <Button icon={<PlusOutlined />} type="primary" htmlType="submit">
              更新
            </Button>
          </Form.Item>
        </Form>
    </Modal>
    {/* 文章详情 */}
    <ArticleDetail 
      isArticleDetailModalOpen={isArticleDetailModalOpen}
      onEvent={handleDetailCancel}
      articleDetail={articleDetail}
    />
  </div>
}


export default ArticleList